package com.example.emos.wx.config.shiro;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.auth0.jwt.JWTVerifier;

import java.util.Date;

/**
 * @ClassName JwtTokenUtils
 * @Description TODO
 * @Author luowenhong
 * @Version 1.0
 **/

@Component
public class JwtTokenUtils {
    /** 携带token的请求头名字 */
    public final static String TOKEN_HEADER = "Authorization";
    /** token的前缀 */
    public final static String TOKEN_PREFIX = "Bearer ";
//    /** 一分钟 */
//    public final static long ONE_MINUTES = 60 * 1000;
//    /** 设置 token 有效期为 30 分钟 */
//    public final static long TOKEN_EXPIRATION = 30 * ONE_MINUTES;
//    /** 续期时间 是token是两倍 */
//    public final static long REDIS_TOKEN_EXPIRATION = 2 * TOKEN_EXPIRATION;

    /** 默认密钥 */
    @Value("${emos.jwt.secret}")
    private String DEFAULT_SECRET;
    /** 过期时间 */
    @Value("${emos.jwt.expire}")
    private Integer expire;

    public String createToken(Integer userId){
        Algorithm algorithm = Algorithm.HMAC256(DEFAULT_SECRET);    // 加密算法
        Date date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, expire).toJdkDate();
        JWTCreator.Builder builder = JWT.create();
        String token = builder.withClaim("userId", userId).withExpiresAt(date).sign(algorithm);
        return token;
    }

    public Integer getUserId(String token){
        Integer userId = 0;
        try {
            DecodedJWT jwt = JWT.decode(token);
            userId = jwt.getClaim("userId").asInt();
        }catch (Exception e){
            e.printStackTrace();
        }
        return userId;
    }

    public void verifierToken(String token) {
        Algorithm algorithm = Algorithm.HMAC256(DEFAULT_SECRET); //创建加密算法对象
        JWTVerifier verifier = JWT.require(algorithm).build();
        verifier.verify(token);
    }

}
